package com.fesine.quartz.chapter5;

import com.fesine.quartz.chapter4.PrintJob;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * @description: 演示cron表达式定时器
 * @author: Fesine
 * @createTime:2016/11/18 23:12
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/11/18 23:12
 */
public class Listing_5_1 {
    static Log logger = LogFactory.getLog(Listing_5_1.class);

    public static void main(String[] args) {
        Listing_5_1 example = new Listing_5_1();
        example.runScheduler();
    }

    public void runScheduler() {
        Scheduler scheduler = null;

        try {
            // Create a default instance of the Scheduler
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            logger.info("Scheduler was started at " + new Date());

            // Create the JobDetail
            JobDetail jobDetail =
                    new JobDetail("PrintInfoJob",
                            Scheduler.DEFAULT_GROUP,
                            PrintJob.class);

            // Create a CronTrigger
            try {
                // CronTrigger 周一到周四每5秒钟触发一次
                CronTrigger trigger1 = new
                        CronTrigger("CronTrigger", null,"0/5 * * ? * MON-FRI");
                scheduler.scheduleJob(jobDetail, trigger1);
                //定时每天14点到19点整点触发,并且设置开始和结束日期
                CronTrigger trigger2 = new CronTrigger("myTrigger", null, "0 0 14-20 * * ?");
                Calendar cal = Calendar.getInstance();
                //当前日期+1天
                cal.add(Calendar.DATE, 1);
                trigger2.setStartTime(cal.getTime());
                //结束日期为再后面2天
                cal.add(Calendar.DATE, 2);
                trigger2.setEndTime(cal.getTime());
                scheduler.scheduleJob(jobDetail, trigger2);
                //使用TriggerUtils创建cronTrigger，需求是每天17点30触发
                // 传统做法是0 30 17 ? * *
                Trigger trigger3 = TriggerUtils.makeDailyTrigger(17, 30);
                trigger3.setName("trigger3");
                scheduler.scheduleJob(jobDetail, trigger3);
                //创建立即只触发一次的定时器
                Trigger trigger4 = TriggerUtils.makeImmediateTrigger(0, 0);
                trigger4.setName("trigger4");
                scheduler.scheduleJob(jobDetail, trigger4);
            } catch (ParseException ex) {
                logger.error("Error parsing cron expr", ex);

            }


        } catch (SchedulerException ex) {
            logger.error(ex);
        }
    }
}

